import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import {
  ProcurementCooperationGetContractNumber,
  SupplierEnterpriseInfoGetLockedInfo,
  ProcurementCooperationCreate,
  ProcurementCooperationGetAllByPagedAndSort,
  ProcurementCooperationGetInfo
} from "@/api/stu/SupplyChainFinance";
import { FXQ } from "@/utils/public/FXQ"
import * as echarts from 'echarts';
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
export function useSupplierWarehouse() {
  const route = useRoute();
  const isSeal = ref<boolean>(false)
  const isShowDetail = ref(false)
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "供应商企业名称",
      prop: "secondParty",
    },
    {
      label: "签订协议日期",
      prop: "purchaseDate",
    },
    {
      label: '签订状态',
      prop: "signStatus",
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.signStatus == 0 ? "warning" : "success"}>
          {
            row.signStatus == 0 ? "未签订" : "已签订"
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 140,
      slot: "operation"
    }
  ];
  const ContractNumber = ref<string>("");
  const FirstParty = ref<string>("")
  const Vdialog = ref(false);
  const dataList = ref([])
  const loading = ref<boolean>(false);
  const contract = reactive({
    seiId: "",
    ProcuringAgent: "xxxx电商企业公司",
    supplier: "",
    DateSigning: "",
    ContractNumber: "",
    FirstParty: "",
    SecondParty: "",
    SigningTime: "",
    createTime: ""
  })
  // 获取合同编号
  async function GetContractNumber(date) {
    let data = qs.stringify({
      selectedDate: date,
      taskId: route.query.taskId,
      planId: route.query.planId
    })
    const res = await ProcurementCooperationGetContractNumber(data);
    if (res.success) {
      contract.ContractNumber = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }
  // 获取已经锁定的供应商成功  -- 供应方名称
  async function GetLockedInfo() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    }
    const res = await SupplierEnterpriseInfoGetLockedInfo(data);
    if (res.success) {
      contract.supplier = res.data.supplyName;
      contract.seiId = res.data.seiId;
      contract.createTime = res.data.createTime;
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 盖章
  function Signet() {
    // const state = powerattorney_.value.seal();
    // const datas_ = powerattorney_.value.RepotFrom2;
    if (!contract.supplier) {
      ElMessage.warning("请先锁定供应商")
      return
    }
    // // 生成章
    const MYFXQ = FXQ.companySeal(contract.supplier, 0, 0, '', '');
    let view_FQX = document.querySelector("#view_FQX");
    let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
    view_FQX.innerHTML = MYFQX;
    isSeal.value = true
  }

  function ClosePanelVisible() {
    contract.supplier = ""
    contract.DateSigning = ""
    contract.ContractNumber = ""
    contract.FirstParty = ""
    contract.SecondParty = ""
    contract.SigningTime = ""
    Vdialog.value = false
    isShowDetail.value = false
    isSeal.value = false
  }

  async function addCase() {
    if (contract.DateSigning == "" || contract.DateSigning == null) {
      ElMessage.warning("未选择签订日期")
      return
    }
    if (!isSeal.value) {
      ElMessage.warning("乙方未盖章")
      return
    }
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      seiId: contract.seiId,
      purchaseDate: contract.DateSigning,
      createTime: contract.createTime,
      procuringAgency: contract.ProcuringAgent,
      owner: contract.ProcuringAgent,
      secondParty: contract.supplier,
      contractNumber: contract.ContractNumber
    };
    const res = await ProcurementCooperationCreate(data);
    if (res.success) {
      ElMessage.success(res.msg);
      getClientBaseData()
      ClosePanelVisible()
    } else {
      ElMessage.error(res.msg);
    }
  }
  // 分页获取采购合作协议列表
  async function getClientBaseData() {
    const data = {
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
      taskId: route.query.taskId,
      planId: route.query.planId,
      SEIId: sessionStorage.getItem("seiId"),
    }
    const res = await ProcurementCooperationGetAllByPagedAndSort(data);
    if (res.success) {
      res.data.items.forEach(item => {
        item.purchaseDate = item.purchaseDate.substring(0, 10)
      })
      dataList.value = res.data.items;
      pagination.total = res.data.totalCount
    } else {
      ElMessage.error(res.msg)
    }
  }

  async function showDetail(row) {
    const data = qs.stringify({
      id: row.procurementCooperationId,
    })
    const res = await ProcurementCooperationGetInfo(data);
    if (res.success) {
      Vdialog.value = true
      isShowDetail.value = true
      contract.ProcuringAgent = "xxxx电商企业公司"
      contract.supplier = res.data.supplyName
      contract.DateSigning = res.data.purchaseDate
      contract.ContractNumber = res.data.contractNumber
    } else {
      ElMessage.error(res.msg)
    }
    nextTick(() => {
      const MYFXQ = FXQ.companySeal(contract.supplier, 0, 0, '', '');
      let view_FQX = document.querySelector("#view_FQX");
      let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
      view_FQX.innerHTML = MYFQX;
      isSeal.value = true
      if (row.signStatus == 2) {
        const MYFXQ = FXQ.companySeal(contract.ProcuringAgent, 0, 0, '', '');
        let view_FQX = document.querySelector("#view_FQXS");
        let MYFQX = `<img src='${MYFXQ}' style="width:100%;height:100%"  />`
        view_FQX.innerHTML = MYFQX;
      }
    })
  }
  function ClickVdialog() {
    Vdialog.value = true;
    GetLockedInfo()
  }

  onMounted(() => {
    getClientBaseData()
  })

  function handleSizeChange() {
    getClientBaseData()
  }
  function handleCurrentChange() {
    getClientBaseData()
  }

  function changeDate() {
    if (contract.DateSigning !== null) {
      GetContractNumber(contract.DateSigning)
    }
  }

  return {
    isSeal,
    columns,
    Vdialog,
    dataList,
    loading,
    contract,
    ContractNumber,
    ClosePanelVisible,
    ClickVdialog,
    addCase,
    Signet,
    showDetail,
    isShowDetail,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    changeDate,
  }
}
